<template>
  <div class="page member-analysis">
    <StoreChoice
      ref="StoreChoice"
      :current="currentShop"
      v-if="role==='1'"
      :multipleChoice="false"
      v-on:listenToStoreSelect="getSelectStoreValue"
      :hasTotal="false"
      reqUrl="/applet/manager/queryCityShopList.do?queryType=2&serviceCode=10"
    />
    <div class="scroll-view">
      <customHeader middleTitle="会员分析" @leftCallBack="handleBack"/>
      <div class="page-body">
        <ul class="filter">
          <li v-if="role==='1'" @click="handleClickSelectStore">
            <span>{{storeName}}</span>
            <i class="zhk-list_rarrow"></i>
          </li>
          <li v-else>
            <span>{{storeName}}</span>
          </li>
        </ul>

        <div class="get-way">
          <div class="trade-summary">
            <div class="ts-content">
              <ul class="bottom">
                <li>
                  <div class="money">
                    <span>今日新增会员数(人)</span>
                    <div>{{ringSource.newCustomerCount}}</div>
                  </div>
                </li>
                <li>
                  <div class="money">
                    <span>会员总数</span>
                    <div>{{ringSource.totalCustomerCount}}</div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
          <div class="ring-title">忠实会员占比</div>
          <div class="section chart-wrap">
            <ve-ring :data="ringData" :settings="chartRingSettings" :legend="ringLegend" :extend="ringExtend"></ve-ring>
            <p class="chart-remark">
              备注：
              <br>高频消费会员：交易2次及以上会员；
              <br>低频消费会员：只交易过1次的会员；
            </p>
          </div>
        </div>

        <div class="zhk-statistics">
          <div class="section-title">新增会员趋势分析</div>
          <div class="section-container">
            <ul class="tab-bar">
              <li
                class="checked"
                :key="index"
                v-for="(item,index) in tabCompent.tabList"
                @click="toggleTab(tabCompent,index)"
                :class="{selected:index == tabCompent.tabIndex}"
              >{{item.label}}</li>
            </ul>
          </div>
          <div class="chart-tips">
            时段内新增会员数：
            <span>{{lineSource.newCustTotalCount}}</span>人
            环比：
            <span>{{lineSource.chainRatio}}</span>
          </div>
          <div class="section chart-wrap">
            <ve-line :data="lineData" :settings="chartSettings2" :yAxis="lineYAxis"></ve-line>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Toast } from "mint-ui";
import config from "../../base/profile/config.json";
import jsBridge from "../../tools/jsBridge.js";
import customHeader from "../../components/header/header";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import DateChoice from "../../components/DateChoice/DateChoice";
import { Popup } from "mint-ui";
Vue.component(Popup.name, Popup);
export default {
  name: "memberAnalysis",
  data() {
    this.lineYAxis = {
      type: 'value',
      minInterval: 1,
    };
    this.ringLegend = {
      selectedMode: false,
    },
    this.ringExtend = {
        series (v) {
          v.forEach(i => {
            i.silent=true;
          })
          return v
        },
      }
      this.chartRingSettings = {
        dimension: "type",
        metrics: "amount",
        label: {
          position: "center",
          formatter: (param) => {
            return "\n\n" + param.name + "\n\n" + param.value + " (" + param.percent + "%)";
          },
          fontSize: 12,
        },
        labelLine: {
          show: false,
        }
      };
    this.chartSettings = {
      dimension: "type",
      metrics: "amount"
    };
    this.chartSettings2 = {
      yAxisName: ["单位:人"],
      type: 'value',
      minInterval: 1,
      yAxis: {
        type: 'value',
        minInterval: 1,
      }
    };
    return {
      currentShop: [],
      role: "",
      shopId: "",
      ringSource: {
        newCustomerCount: 0,//新增会员人数
        totalCustomerCount: 0,//会员总数
        todayGrtTwiceCustomerCount: 0,//今日忠实会员总数
        totalGrtTwiceCustomerCount: 0,//忠实会员总数
      },
      lineSource: {
        dateSlot: 7,//时间段7，30,90
        newCustTotalCount: 0,//新增会员人员总数
        preSlotNewCustTotalCount: 0,//上一个周期的新增会员总数
        chainRatio: "--",
        shopCustomerSummaryList: []//时间段，每天数据汇总列表
      },
      filterData: {},
      storeName: "",
      tabCompent: {
        tabList: [
          { label: "近7天", value: 7 },
          { label: "近30天", value: 30 },
          { label: "近90天", value: 90 }
        ],
        tabIndex: 0
      },
      dataList: [],
      chartData: {
        columns: ["type", "amount"],
        rows: []
      },
      ringData: {
        columns: ["type", "amount"],
        rows: [
          // { type: "高频消费会员", amount: 0 },
          // { type: "低频消费会员", amount: 0 }
        ]
      },
      lineData: {
        columns: ["日期", "新增会员数"],
        rows: [
          // { 日期: "2019-4-09", 新增会员数: 1 },
          // { 日期: "2019-4-10", 新增会员数: 3 },
          // { 日期: "2019-4-11", 新增会员数: 5 },
          // { 日期: "2019-4-12", 新增会员数: 2 }
        ]
      },
    };
  },
  methods: {
    handleClickSelectStore() {
      this.$refs.StoreChoice.popupShow();
    },
    handleBack() {
      if (this.$refs.StoreChoice && this.$refs.StoreChoice.popupVisible){
        this.$refs.StoreChoice.back();
      } else {
        if (String(this.$route.query.close) == "true") {
          jsBridge.closeWindow();
        } else {
          this.$router.back();
        }
      }
    },
    toggleTab(tabCompent, index) {
      tabCompent.tabIndex = index;
      this.getLineData();
    },
    getSelectStoreValue(value, storeName) {
      this.shopId = value[0].selectKey == "all" ? "" : value[0].selectKey;
      this.storeName = storeName;
      this.getRingData();
      this.getLineData();
    },
    getRingData() {
      this.ajax({
        url: `/applet/member/getMemberAnalyzeAccount.do?selfShopId=${this.shopId}`,
        type: "get",
        controlLoading: false
      })
        .then((res) => {
          if (res.success) {
            const ringSource = res.resultObject;
            this.ringSource = ringSource;
            this.ringData.rows = [
              { type: "高频消费会员", amount: ringSource.totalGrtTwiceCustomerCount },
              { type: "低频消费会员", amount: ringSource.totalCustomerCount - ringSource.totalGrtTwiceCustomerCount }];
          }
        })
        .catch(function (err) {

        });
    },
    //转换百分比
    toPercent(point) {
      var str = Number(point * 100).toFixed(1);
      str += "%";
      return str;
    },
    getLineData() {
      let dateSlot = this.tabCompent.tabList[this.tabCompent.tabIndex].value;
      this.ajax({
        url: `/applet/member/getMemberAnalyze.do?selfShopId=${this.shopId}&dateSlot=${dateSlot}`,
        type: "get",
        controlLoading: false
      })
        .then((res) => {
          if (res.success) {
            const data = res.resultObject;
            const shopCustomerSummaryList = data.shopCustomerSummaryList;
            this.lineSource = data;
            if(data.preSlotNewCustTotalCount){
               const chainRatio = (data.newCustTotalCount - data.preSlotNewCustTotalCount) / data.preSlotNewCustTotalCount ;
               this.lineSource.chainRatio = this.toPercent(chainRatio);
            }else{
               this.lineSource.chainRatio = "--";
            }

            let rows = [];
            for (var i = 0; i < shopCustomerSummaryList.length; i++) {
              rows.push({
                日期: shopCustomerSummaryList[i].bizDate,
                新增会员数: shopCustomerSummaryList[i].newCustomerCount
              });
            }
            this.lineData.rows = rows;
          }
        })
        .catch(function (err) {

        });
    },
    getShopList() {
      this.ajax({
        url: `/applet/manager/queryCityShopList.do?queryType=2&serviceCode=10`,
        type: "get",
        controlLoading: false
      })
        .then((res) => {
          if (res.success) {
            const data = res.resultObject;
            let shopList = [];
            if (data != null && JSON.stringify(data) != "{}") {
              for (var cityName in data) {
                if (data[cityName] != null && data[cityName].length > 0) {
                  for (var i = 0; i < data[cityName].length; i++) {
                    //未开通小程序或者不满足条件的门店（mini：已开通小程序 true:开通；  passMini：符合小程序开通 true:符合 false:不符合）
                    if (data[cityName][i]['passMini']) {
                      shopList.push({
                        shopId: data[cityName][i].shopId,
                        shopName: data[cityName][i].shopName,
                      });
                    }
                  }
                }
              }
            }

            if (shopList.length) {
              this.shopId = shopList[0].shopId;
              this.storeName = shopList[0].shopName;
              this.currentShop = [{ selectKey: shopList[0].shopId }];
              this.getRingData();
              this.getLineData();
            }
          }
        })
        .catch(function (err) {

        });
    },

  },
  mounted() { },
  created() {
    CommonUtil.getUserInfo().then(userInfo => {
      this.role = userInfo.role;
      this.shopId = userInfo.yzShopId;
      this.storeName = userInfo.shopName;
      if (userInfo.manyShopFlag) {
        this.getShopList();
      } else {
        this.getRingData();
        this.getLineData();
      }

    });

  },
  components: {
    customHeader,
    StoreChoice
  }
};
</script>
<style lang='scss' scoped>
@import "memberManage";
</style>
